// src/store/taskStore.js
import { defineStore } from 'pinia';

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [],
    undoStack: [],
    sortBy: 'date',
    sortDirection: 'desc',
    searchQuery: ''
  }),

  actions: {
    // 批量标记完成/未完成
    batchToggleCompleted(ids, completed) {
      const changes = [];
      ids.forEach(id => {
        const taskIndex = this.tasks.findIndex(task => task.id === id);
        if (taskIndex !== -1) {
          changes.push({
            id,
            oldState: { ...this.tasks[taskIndex] }
          });
          this.tasks[taskIndex].completed = completed;
        }
      });
      if (changes.length > 0) {
        this.undoStack.push({ type: 'batchToggle', changes });
        this.saveTasks();
      }
    },

    // 批量删除任务
    batchDelete(ids) {
      const deletedTasks = [];
      // 从后往前删除，避免索引变化
      ids.sort((a, b) => b - a).forEach(id => {
        const taskIndex = this.tasks.findIndex(task => task.id === id);
        if (taskIndex !== -1) {
          deletedTasks.push({
            task: this.tasks[taskIndex],
            index: taskIndex
          });
          this.tasks.splice(taskIndex, 1);
        }
      });
      if (deletedTasks.length > 0) {
        this.undoStack.push({ type: 'batchDelete', deletedTasks });
        this.saveTasks();
      }
    },

    // 批量更新优先级
    batchUpdatePriority(ids, priority) {
      const changes = [];
      ids.forEach(id => {
        const taskIndex = this.tasks.findIndex(task => task.id === id);
        if (taskIndex !== -1 && this.tasks[taskIndex].priority !== priority) {
          changes.push({
            id,
            oldState: { ...this.tasks[taskIndex] }
          });
          this.tasks[taskIndex].priority = priority;
        }
      });
      if (changes.length > 0) {
        this.undoStack.push({ type: 'batchPriority', changes, priority });
        this.saveTasks();
      }
    },

    // 撤销操作增强
    undo() {
      if (this.undoStack.length === 0) return;
      const action = this.undoStack.pop();
      
      switch (action.type) {
        // 原有撤销操作保持不变...
        
        case 'batchToggle':
          action.changes.forEach(change => {
            const taskIndex = this.tasks.findIndex(task => task.id === change.id);
            if (taskIndex !== -1) {
              this.tasks[taskIndex].completed = change.oldState.completed;
            }
          });
          break;
          
        case 'batchDelete':
          action.deletedTasks.forEach(item => {
            this.tasks.splice(item.index, 0, item.task);
          });
          break;
          
        case 'batchPriority':
          action.changes.forEach(change => {
            const taskIndex = this.tasks.findIndex(task => task.id === change.id);
            if (taskIndex !== -1) {
              this.tasks[taskIndex].priority = change.oldState.priority;
            }
          });
          break;
      }
      this.saveTasks();
    }
  }
}); 增加功能和页面